package com.swt.gap.service.impl;

import com.swt.gap.dao.SysDepartmentDao;
import com.swt.gap.model.entity.SysDepartment;
import com.swt.gap.model.vo.SysDepartmentTreeVO;
import com.swt.gap.service.SysDepartmentService;
import com.swt.gap.util.TreeUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author sx
 */
@Service
public class SysDepartmentServiceImpl implements SysDepartmentService {

    public static int FAKE_PARENT_ID = -1;
    public static int ROOT_PARENT_ID = 0;

    private final SysDepartmentDao sysDepartmentDao;

    public SysDepartmentServiceImpl(SysDepartmentDao sysDepartmentDao) {
        this.sysDepartmentDao = sysDepartmentDao;
    }

    @Override
    public Integer addDepartment(SysDepartment department) {
        if (department.getParentDepartmentId().equals(FAKE_PARENT_ID)) {
            department.setParentDepartmentId(ROOT_PARENT_ID);
        }
        return sysDepartmentDao.insertSelective(department);
    }

    @Override
    public SysDepartment getDepartment(Integer departmentId) {
        return sysDepartmentDao.selectByPrimaryKey(departmentId);
    }

    @Override
    public List<SysDepartmentTreeVO> listDepartment() {
        List<SysDepartmentTreeVO> sysDepartmentTrees = new ArrayList<>();
        List<SysDepartment> sysDepartments = sysDepartmentDao.selectAll();

        sysDepartments.forEach(dept -> {
            SysDepartmentTreeVO treeNode = new SysDepartmentTreeVO();
            BeanUtils.copyProperties(dept, treeNode);
            treeNode.setId(dept.getDepartmentId().toString());
            treeNode.setParentId(dept.getParentDepartmentId().toString());
            sysDepartmentTrees.add(treeNode);
        });
        List<SysDepartmentTreeVO> retValue = TreeUtil.build(sysDepartmentTrees, String.valueOf(ROOT_PARENT_ID));

        // 有点奇怪的原型设计，强行加一个一级而不是0级
        SysDepartmentTreeVO rootDept = SysDepartmentTreeVO.builder()
                .departmentId(FAKE_PARENT_ID)
                .departmentName("无上级部门")
                .parentDepartmentId(ROOT_PARENT_ID)
                .hidden(true)
                .build();
        retValue.add(0, rootDept);
        return retValue;
    }

    @Override
    public Integer updateDepartment(SysDepartment department) {
        if (department.getParentDepartmentId().equals(FAKE_PARENT_ID)) {
            department.setParentDepartmentId(ROOT_PARENT_ID);
        }
        return sysDepartmentDao.updateByPrimaryKeySelective(department);
    }

    @Override
    public Integer deleteDepartment(Integer departmentId) {
        return sysDepartmentDao.deleteByPrimaryKey(departmentId);
    }

    @Override
    public List<SysDepartment> listChildrenDepartments(Integer departmentId) {
        return null;
    }
}
